const items = [first, second, third];
let activeIndex = 0;

function handleCarousel(oldActive, oldNext) {
  setUp(oldActive, oldNext);
  doCarousel();
  cleanup(oldActive, oldNext);

  function doCarousel() {
    for (let index = 0; index < items.length; index++) {
      const finalIndex = processIndex(activeIndex, index);
      const distance = 300 * (finalIndex - activeIndex);
      items[index].style.transform = `translateX(${distance}px)`;
    }
  }

  function processIndex(activeIndex = 0, index) {
    if (activeIndex === 0 && index === items.length - 1) {
      return -1;
    } else if (activeIndex === items.length - 1 && index === 0) {
      return items.length;
    }
    return index;
  }

  function cleanup(oldActive, oldNext) {
    // 浏览器渲染
    document.body.offsetHeight;
    items[oldActive].style.transitionDuration = "0s";
    items[oldNext].style.transitionDuration = "0s";
    items[oldActive].style.zIndex = "0";
    items[oldNext].style.zIndex = "0";
  }

  function setUp(oldActive, oldNext) {
    items[oldActive].style.transitionDuration = ".5s";
    items[oldNext].style.transitionDuration = ".5s";
    items[oldActive].style.zIndex = "999";
    items[oldNext].style.zIndex = "999";
  }
}

right.addEventListener("click", () => {
  let oldActiveIndex = activeIndex;
  activeIndex++;
  if (activeIndex === items.length) activeIndex = 0;
  let oldNext = activeIndex;
  handleCarousel(oldActiveIndex, oldNext);
});

left.addEventListener("click", () => {
  let oldActiveIndex = activeIndex;
  activeIndex--;
  if (activeIndex < 0) activeIndex = items.length - 1;
  let oldPrev = activeIndex;
  handleCarousel(oldActiveIndex, oldPrev);
});

handleCarousel(activeIndex,activeIndex + 1)